from fastapi import Request
from pydantic import BaseModel
from tortoise.transactions import atomic, in_transaction

from service import UserService
from service import RepositoryService
from common.result.Result import Result
from common.enum import BaseEnum
from util.str import Str
from util.log import Log
from util.token import Token
from util.time import Time

class Body(BaseModel):
    shortUri: str

async def UpdateRepository(req: Request, body: dict):
    try:
        async with in_transaction() as connection:
            token = req.headers.get("token")
            shortUri = body.get("shortUri")
            if Str.isBlank(token, shortUri):
                Log.error('参数为空，检查参数')
                return Result.error(BaseEnum.PARAMETER_INVALID_ERROR)

            user = await UserService.getUserByToken(token)
            if user == None:
                Log.error('user 不存在', user)
                return Result.error(BaseEnum.USER_NOT_EXISTS_ERROR)
            
            repository = await RepositoryService.getRepositoryByShortUri(shortUri)
            if repository == None:
                return Result.error(BaseEnum.REPOSITORY_NOT_EXISTS_ERROR)
            
            if repository.user_id != user.id:
                Log.error('非创建者不可修改知识库')
                return Result.error(BaseEnum.REPOSITORY_NO_WRITE_PERMISSION_ERROR)
            
            cnt = await RepositoryService.updateRepositoryByShorturi(shortUri, body)
            return Result.success(cnt)  
    except Exception as e:
        Log.error('更新知识库异常', e)
        return Result.error(BaseEnum.SERVICE_ERROR)


